const { Op, literal } = require("sequelize");
const User = require("../models/User.js");

class UserService {
    async addUser(userData){
        return User.create(userData);
    }
    async getUserById(id, transaction){
        return User.findByPk(id, {
            attributes: [
                'id',
                'email',
                'status',
                'password',
                'page',
                [literal('DATE_FORMAT(User.membershipExpireAt, "%Y-%m-%d %H:%i:%s")'), 'membershipExpireAt'],
            ],
            transaction
        });
    }
    async getUserByEmail(email, transaction){
        return User.findOne({
            where: {
                email,
                deleted_at: null
            },
            transaction
        });
    }
    async updateUser(userData){
        return User.update(userData, {
            where: {
                id: userData.id
            }
        });
    }
    async deleteUser(userId){
        return User.destroy({
            where: {
                id: userId
            }
        });
    }
    async getUserListByPage(page = 1, limit = 10, keyword){
        return User.findAndCountAll({
            limit,
            offset: (page - 1) * limit,
            distinct: true,
            where: {
                deleted_at: null,
                [Op.or]: [
                    {
                      email: {
                        [Op.like]: `%${keyword}%`,
                      },
                    },
                  ],
            },
            attributes: [
                'id',
                'email',
                'status',
                'page',
                [literal('DATE_FORMAT(User.created_at, "%Y-%m-%d %H:%i:%s")'), 'created_at'],
                [literal('DATE_FORMAT(User.updated_at, "%Y-%m-%d %H:%i:%s")'), 'updated_at'],
                [literal('DATE_FORMAT(User.deleted_at, "%Y-%m-%d %H:%i:%s")'), 'deleted_at'],
                [literal('DATE_FORMAT(User.membershipExpireAt, "%Y-%m-%d %H:%i:%s")'), 'membershipExpireAt'],
            ]
        });
    }
}

module.exports = new UserService();